package com.example.rxjavautildemo.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.rxjavautildemo.R;
import com.example.rxjavautildemo.base.BaseActivity;
import com.xuexiang.rxutil2.lifecycle.RxLifecycle;
import com.xuexiang.rxutil2.logs.RxLog;
import com.xuexiang.rxutil2.rxjava.DisposablePool;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;
import com.xuexiang.rxutil2.rxjava.task.RxIteratorTask;
import com.xuexiang.rxutil2.rxjava.task.RxUITask;
import com.xuexiang.rxutil2.subsciber.ProgressDialogLoader;
import com.xuexiang.rxutil2.subsciber.ProgressLoadingSubscriber;
import com.xuexiang.rxutil2.subsciber.SimpleSubscriber;
import com.xuexiang.rxutil2.subsciber.impl.IProgressLoader;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongBinaryOperator;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class RxJavaActivity extends BaseActivity {
    public static final String TAG = "RxJavaUtils";
    private IProgressLoader mProgressLoader;
    @BindView(R.id.btn_count_down)
    Button mBtnCountDown;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_rx_java;
    }

    @Override
    protected void initViews() {
        mProgressLoader = new ProgressDialogLoader(this,"正在加载，请稍后...");
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.btn_do_in_io,R.id.btn_do_in_ui,R.id.btn_do_in_io_ui,R.id.btn_loading,
    R.id.btn_polling,R.id.btn_count_down,R.id.btn_foreach,R.id.btn_oom_test,R.id.btn_oom_resolve})
    protected void onViewClicked(View view){
        switch (view.getId()) {
            case R.id.btn_do_in_io:
                RxJavaUtils.doInIOThread(new RxIOTask<String>("我是入参123") {
                    @Override
                    public Void doInIOThread(String s) {
                        Log.e(TAG,"[doInIOThread] " + getLooperStatus() + ",入参：" + s);
                        return null;
                    }
                });
                break;
            case R.id.btn_do_in_ui:
                RxJavaUtils.doInUIThread(new RxUITask<String>("我是入参456") {
                    @Override
                    public void doInUIThread(String s) {
                        Log.e(TAG,"[doInUIThread] " + getLooperStatus() + ",入参:" + s);
                    }
                });
                break;
            case R.id.btn_do_in_io_ui:
                RxJavaUtils.executeAsyncTask(new RxAsyncTask<String, Integer>("我是入参789") {
                    @Override
                    public Integer doInIOThread(String s) {
                        Log.e(TAG,"[doInIOThread] " + getLooperStatus() + ", 入参:" + s);
                        return 123;
                    }

                    @Override
                    public void doInUIThread(Integer integer) {
                        Log.e(TAG,"[doInUIThread] " + getLooperStatus() + ",入参：" + integer);
                    }
                });
                break;
            case R.id.btn_loading:
                RxJavaUtils.delay("加载完毕！", 3, TimeUnit.SECONDS, new ProgressLoadingSubscriber<String>(mProgressLoader) {
                    @Override
                    public void onSuccess(String s) {
                        Toast.makeText(RxJavaActivity.this, s, Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.btn_polling:
                RxJavaUtils.polling(5)
                        .compose(RxLifecycle.with(this).bindToLifecycle())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                toast("正在监听：" + aLong);
                            }
                        });
                break;
            case R.id.btn_count_down:
                DisposablePool.get().add(RxJavaUtils.countDown(30, new SimpleSubscriber<Long>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        mBtnCountDown.setEnabled(false);
                    }

                    @Override
                    public void onSuccess(Long aLong) {
                        mBtnCountDown.setText(String.format("%s s后重新获取",aLong));
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mBtnCountDown.setText("重新获取");
                        mBtnCountDown.setEnabled(true);
                    }
                }),"countDown");
                break;
            case R.id.btn_foreach:
                List<String> items = Arrays.asList("李治","遇广亮","杨金勇","王迪","曹文倩");
                RxJavaUtils.executeRxIteratorTask(new RxIteratorTask<String, String>(items) {
                    @Override
                    public String doInIOThread(String s) {
                        return "你好：" + s;
                    }

                    @Override
                    public void doInUIThread(String s) {
                        Log.e(TAG,s);
                    }
                });
                break;
            case R.id.btn_oom_test:
                for (int i = 0; i < 10000; i++) {
                    test();
                }
                break;
            default:
                break;
        }
    }

    public String getLooperStatus(){
        return "当前线程状态：" + (Looper.myLooper() == Looper.getMainLooper() ? "主线程" : "子线程");
    }

    @SuppressLint("CheckResult")
    private void test(){
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                try {
                    Thread.sleep(100000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emitter.onNext(3);
                emitter.onComplete();
            }
        }).compose(RxSchedulerUtils._io_main_o()).subscribe(new SimpleSubscriber<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                ToastUtils.toast("索引：" + integer);
            }
        });
    }
}
